<template>
  <div>
    <el-card style="margin: 20px 0">
      <el-button type="primary" icon="el-icon-search" @click="searchAction" style="">查询</el-button>
    </el-card>
    <el-card>
      <div>
        <el-button type="primary" @click="showDialogAction(null)" icon="el-icon-plus" style="margin: 0 0 10px 0">
          新增SPU
        </el-button>

        <el-table border="border" v-loading="loading" :data="tableData" style="width: 100%">
          <el-table-column align="center" type="index" label="序号" width="80"></el-table-column>
          <el-table-column prop="spuSimpleName" label="Spu简称" width="250"></el-table-column>
          <el-table-column prop="spuName" label="Spu全称" width="600"></el-table-column>
          <el-table-column prop="spuPrice" label="Spu售卖价格(元)"></el-table-column>
          <el-table-column prop="spuLinePrice" label="Spu划线价格(元)"></el-table-column>
          <el-table-column prop="spuStatus" label="状态" width="120">
            <template slot-scope="scope">
              <el-tag :type="enumFormat(scope.row.spuStatus).color">{{ enumFormat(scope.row.spuStatus).label }}</el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="updateTime" label="编辑时间" width="140"></el-table-column>
          <el-table-column prop="updateBy" label="编辑人" width="100"></el-table-column>


          <el-table-column prop="prop" label="操作" align="center" fixed="right" width="120">
            <template slot-scope="{row,$index}">
              <el-button @click="showDialogAction(row)" type="primary" icon="el-icon-edit" circle></el-button>
              <el-button @click="delAction(row)" type="danger" icon="el-icon-delete" circle></el-button>
            </template>
          </el-table-column>


        </el-table>
      </div>
    </el-card>

    <!--    z-index="100"-->

    <el-drawer
      title="我是标题"
      :visible.sync="dialogFormVisible"
      :direction="direction"
      size="70%"
      :before-close="handleClose"
    >
      <div style="padding: 0 40px 40px 40px">
        <el-form :model="form" ref="ruleForm" :rules="rules">

          <el-form-item label="模型名称" prop="modelId" label-width="80px">
            <el-select v-model="form.modelId" @change="handleChangeModelAction" placeholder="请选择">
              <el-option
                v-for="item in allModels"
                :key="item.modelId"
                :label="item.modelName"
                :value="item.modelId"
              >
              </el-option>
            </el-select>
          </el-form-item>


          <el-form-item label="商品简称" placeholder="请输入商品简称" prop="spuName" label-width="80px">

            <el-upload
              :action="fileUploadBanner"
              list-type="picture-card"
              :file-list="fileSpuBannerList"
              :on-success="handleSpuBannerSuccess"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
            >
              <i class="el-icon-plus"></i>
            </el-upload>


          </el-form-item>


          <el-form-item label="商品简称" placeholder="请输入商品简称" prop="spuName" label-width="80px">
            <el-input v-model="form.spuSimpleName" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="商品全称" placeholder="请输入商品全称" prop="spuName" label-width="80px">
            <el-input v-model="form.spuName" autocomplete="off"></el-input>
          </el-form-item>

          <el-form-item label="售卖价格" placeholder="请输入售卖价格" prop="spuPrice" label-width="80px">
            <el-input style="width: 100%;height: 100%" :minLength="1" :maxlength="10" v-model="form.spuPrice"

            ></el-input>
          </el-form-item>
          <el-form-item label="划线价格" placeholder="请输入划线价格" prop="spuLinePrice" label-width="80px">
            <el-input style="width: 100%;height: 100%" :minLength="1" :maxlength="10" v-model="form.spuLinePrice"
            ></el-input>
          </el-form-item>
          <el-form-item label="销量" placeholder="请输入销量" prop="spuSalesVolume" label-width="80px">
            <el-input-number v-model="form.spuSalesVolume" style="width: 120px" @change="handleChangeSpuSalesVolume"
                             :min="1" :max="10000"
                             label="销量"
            ></el-input-number>
          </el-form-item>
          <el-form-item label="状态" label-width="80px">
            <el-radio-group v-model="form.spuStatus">
              <el-radio :label="0">上架</el-radio>
              <el-radio :label="1">下架</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="服务" prop="checkedServiceCodes" label-width="80px">
            <el-checkbox-group v-model="form.checkedServiceCodes">
              <el-checkbox v-for="(item, index) in allServiceCodesList"
                           :key="item.serviceCode"
                           :label="item.serviceCode"
                           name="checkedServiceCodes"
                           @change="handleCheckboxChange(item, $event)"
              >
                {{ item.serviceName }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>

          <el-form-item label="商品详情" placeholder="请输入商品简称" prop="spuName" label-width="80px">

            <el-upload
              :action="fileUploadBanner"
              list-type="picture-card"
              :file-list="fileSpuDetailList"
              :on-success="handleSpuBannerSuccessDetail"
              :on-preview="handlePictureCardPreviewDetail"
              :on-remove="handleRemoveDetail"
            >
              <i class="el-icon-plus"></i>
            </el-upload>


          </el-form-item>

          <el-button type="primary" icon="el-icon-plus" @click="addSkuAction">新增SKU
          </el-button>

          <el-table
            :data="form.skuList"
            border
            style="width: 100%;margin-top: 10px"
          >
            <el-table-column align="center" type="index" label="序号" width="50"></el-table-column>

            <!--            <el-table-column-->
            <!--              prop="giftDarkImg"-->
            <!--              label="礼物灰图"-->
            <!--              width="180"-->
            <!--            >-->
            <!--              <template slot-scope="{row,$index}">-->
            <!--                <el-upload action=""-->
            <!--                           :action="fileUpload"-->
            <!--                           :on-success="-->
            <!--                           (response, file,fileList) =>-->
            <!--                             handleSuccess(-->
            <!--                               response,-->
            <!--                               file,-->
            <!--                               fileList-->
            <!--                             )-->
            <!--                         "-->
            <!--                           :file-list="row.skuImageList" list-type="picture" accept="image/*" ref="img-Imggrey"-->
            <!--                           :limit="1"-->
            <!--                >-->
            <!--                  <el-button size="small" type="primary">点击选择图片</el-button>-->
            <!--                  <div slot="tip" class="el-upload__tip">只能上传jpg/png文件</div>-->
            <!--                </el-upload>-->
            <!--              </template>-->
            <!--            </el-table-column>-->


            <el-table-column
              prop="skuName"
              align="center"
              label="规格名称"
            >
              <template slot-scope="{row,$index}">
                <el-input style="width: 100%;height: 100%" :minLength="1" :maxlength="50" v-model="row.skuName"
                          prop="skuName"
                ></el-input>
              </template>
            </el-table-column>


            <el-table-column
              prop="skuStock"
              label="库存"
              align="center"
              width="120"
            >
              <template slot-scope="{row,$index}">
                <el-input-number v-model="row.skuStock" style="width: 100%" @change="handleChange" :min="1" :max="10000"
                                 label="描述文字"
                ></el-input-number>
              </template>
            </el-table-column>

            <el-table-column
              prop="skuCode"
              label="SKU编码"
              align="center"
              width="200"
            >
              <template slot-scope="{row,$index}">
                <el-input style="width: 100%;height: 100%" :maxlength="50" v-model="row.skuCode"
                          prop="skuCode"
                ></el-input>
              </template>
            </el-table-column>

            <el-table-column
              prop="skuPrice"
              width="110"nnnnn
              align="center"
              label="价格(元)"
            >
              <template slot-scope="{row,$index}">
                <el-input style="width: 100%;height: 100%" :minLength="1" :maxlength="10" v-model="row.skuPrice"
                          prop="skuPrice"
                ></el-input>
              </template>
            </el-table-column>

            <el-table-column
              prop="skuId"
              width="110"
              align="center"
              label="skuId"
            >
            </el-table-column>



            <el-table-column
              prop="skuStatus"
              label="启用/禁用"
              align="center"
              width="200"
            >

              <template slot-scope="{row,$index}">
                <el-switch
                  style="display: block;width: 100%;height: 100%"
                  active-color="#13ce66"
                  v-model="row.skuStatus"
                  inactive-color="#ff4949"
                  active-text="启用"
                  @change="handleSwitchChange"
                  inactive-text="禁用"
                >
                </el-switch>
              </template>

            </el-table-column>

          </el-table>
        </el-form>
        <div class="drawer-footer" style="text-align: right;margin-top: 20px">
          <el-button @click="cancelAction('ruleForm')">取 消</el-button>
          <el-button type="primary" @click="addAction">确 定</el-button>
        </div>
      </div>

    </el-drawer>


    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>

  </div>
</template>
<script>
import * as api from './api'

export default {
  name: 'spu',
  data() {
    return {
      title: '新增',
      pageDto: {
        pageNum: 1,
        pageSize: 10
      },
      dialogImageUrl: '',
      dialogVisible: false,

      pageDto2: {
        pageNum: 1,
        pageSize: 10
      },
      total: 0,
      tableData: [],
      loading: false,
      dialogFormVisible: false,

      allModels: [],
      allServiceCodesList: [],
      drawer: false,
      direction: 'rtl',
      form: {
        modelId: null,
        spuSimpleName: '',
        spuPrice: '',
        spuLinePrice: '',
        spuSalesVolume: 0,
        spuStatus: 1,
        checkedServiceCodes: [],
        skuList: [],
        spuBannerList: [],
        spuDetailList: []
      },
      fileSpuBannerList: [],
      fileSpuDetailList: [],
      rules: {
        // modelId: [
        //   { required: true, message: '请选择模型', trigger: 'blur' },
        // ],
        spuName: [
          { required: true, message: '请输入商品全称', trigger: 'blur' }
        ],
        spuSimpleName: [
          { required: true, message: '请输入商品简称', trigger: 'blur' }
        ],
        spuPrice: [
          { required: true, message: '请输入售卖价格', trigger: 'blur' },
          // { type: 'number', message: '价格必须为数字', trigger: 'blur' },
          { validator: this.validatePrice, trigger: 'blur' } // 自定义验证函数
        ],
        spuLinePrice: [
          { required: true, message: '请输入划线价格', trigger: 'blur' },
          // { type: 'number', message: '价格必须为数字', trigger: 'blur' },
          { validator: this.validatePrice, trigger: 'blur' } // 自定义验证函数
        ],
        spuSalesVolume: [
          { required: true, message: '请输入销量', trigger: 'blur' },
          { type: 'number', message: '价格必须为数字', trigger: 'blur' }
        ],
        checkedServiceCodes: [
          { type: 'array', required: true, message: '请选择服务', trigger: 'change' }
        ]
      },
      fileList: []
    }

  },
  mounted() {
    // 组件加载完毕发出请求
    this.pageAction()
    this.mallServiceListAction()

  },
  methods: {
    handleRemove(file, fileSpuBannerList) {
      console.log(file.url.replace(this.filePrefix, ''))
      this.form.spuBannerList = this.form.spuBannerList.filter(item => item !== file.url.replace(this.filePrefix, ''))
      this.fileSpuBannerList = fileSpuBannerList // 使用最新的 fileList 参数来同步更新 fileSpuBannerList
      console.log(this.form.spuBannerList)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleSpuBannerSuccess(res, file, fileSpuBannerList) {
      const imageUrl = res.data.url
      if (imageUrl) {
        this.form.spuBannerList.push(imageUrl)
        this.fileSpuBannerList.push({ url: this.filePrefix + imageUrl }) // 同步更新 fileSpuBannerList
      } else {
        console.error('No valid URL received from server response')
      }
    },

    handleRemoveDetail(file, fileSpuDetailList) {
      console.log(file.url.replace(this.filePrefix, ''))
      this.form.spuDetailList = this.form.spuDetailList.filter(item => item !== file.url.replace(this.filePrefix, ''))
      this.fileSpuDetailList = fileSpuDetailList // 使用最新的 fileList 参数来同步更新 fileSpuBannerList
    },
    handlePictureCardPreviewDetail(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleSpuBannerSuccessDetail(res, file, fileSpuDetailList) {
      const imageUrl = res.data.url
      if (imageUrl) {
        this.form.spuDetailList.push(imageUrl)
        this.fileSpuDetailList.push({ url: this.filePrefix + imageUrl }) // 同步更新 fileSpuBannerList
      } else {
        console.error('No valid URL received from server response')
      }
    },

    searchAction() {
      //刷新页面
      this.pageAction()
    },
    resetForm() {
      this.form = {
        modelId: null,
        spuSimpleName: '',
        spuPrice: '',
        spuLinePrice: '',
        spuSalesVolume: 0,
        spuStatus: 1,
        checkedServiceCodes: [],
        skuList: [],
        spuBannerList: []
      }
    },
    //加载分页
    async pageAction() {

      this.loading = true
      await this.$sleep(500)
      let result = await api.pageRequest(this.pageDto)
      this.tableData = result.data.list
      this.total = result.data.total
      this.loading = false

    },
    //服务list
    async mallServiceListAction() {
      let result = await api.systemParamByMallServiceKeyRequest()
      this.allServiceCodesList = result.data
      // api.systemParamByMallServiceKeyRequest().then(ress => {
      //   this.allServiceList = ress.data
      // })
    },

    handleChangeModelAction(value) {
      this.modelId = value
    },

    handleCheckboxChange(item, value) {
      // console.log(`Checkbox ${item.serviceName} changed to ${value}`);
      // if (value) {
      //   this.form.checkedServiceCodes.push(item.serviceCode)
      //   console.log(this.form.checkedServiceCodes)
      // } else {
      //   this.form.checkedServiceCodes = this.form.checkedServiceCodes.filter(x => x != item.serviceCode)
      // }
      // console.log(this.form.checkedServiceCodes)
    },

    async showDialogAction(row) {
      this.drawer = true
      if (row === null) {
        this.dialogFormVisible = true
        this.title = '新增'
        //浅拷贝、表格不会跟着变
        // this.form = {...row}
      } else {
        //浅拷贝、表格不会跟着变
        this.dialogFormVisible = true
        this.title = '编辑'
        api.detailRequest(row.spuId).then(res => {
          this.form = res.data
          this.fileSpuBannerList = []
          this.fileSpuDetailList = []
          for (let i = 0; i < this.form.spuBannerList.length; i++) {
            this.fileSpuBannerList.push({ 'url': this.filePrefix + this.form.spuBannerList[i] })
          }

          for (let i = 0; i < this.form.spuDetailList.length; i++) {
            this.fileSpuDetailList.push({ 'url': this.filePrefix + this.form.spuDetailList[i] })
          }

        })
      }
    },

    async addSkuAction() {
      this.drawer = true
      this.form.skuList.push({ 'skuName': '', 'skuCode': '', 'skuPrice': '', 'skuStock': 50, 'skuStatus': false })

    },

    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
          this.cancelAction()
        })
        .catch(_ => {
        })
    },

    handleSwitchChange(value) {
      console.log(value)
    },
    handleChange(value) {
      console.log(value)
    },
    handleChangeSpuSalesVolume(value) {
      console.log(value)
    },

    handleSuccess(response, file, fileList) {
      // 假设返回的response中包含了图片的url
      response.data.url = this.filePrefix + response.data.url
      this.form.skuList[index].skuImageList.push(response.data)
    },

    cancelAction() {
      this.$refs.ruleForm.resetFields()
      this.dialogFormVisible = false
      this.resetForm()
      this.fileSpuBannerList = []
      this.fileSpuDetailList = []
    },
    addAction() {
      console.log(this.form)
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          //请求接口

          api.addRequest(this.form).then(res => {
            if (200 === res.code) {
              //关闭弹窗
              this.dialogFormVisible = false
              //弹出提示
              this.$message({
                // message: res.msg,
                message: this.form.spuId === null ? '新增成功' : '编辑成功',
                type: 'success'
              })
              //刷新页面
              this.pageAction()
              //清空form表单
              this.resetForm()
              this.fileSpuBannerList = []
              this.fileSpuDetailList = []
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    delAction(row) {
      this.$confirm('确认删除？')
        .then(_ => {
          api.delRequest(row.spuId).then(res => {
            if (200 === res.code) {
              //弹出提示
              this.$message({
                message: res.msg,
                type: 'success'
              })
              //刷新页面
              this.pageAction()
            }
          })
        })
        .catch(_ => {
        })

    },
    // 自定义验证函数
    validatePrice(rule, value, callback) {
      // console.log('Validating price:', typeof value, value)
      const numValue = parseFloat(value)
      // console.log('Parsed number:', typeof numValue, numValue)

      if (isNaN(numValue) || numValue <= 0) {
        callback(new Error('价格必须是大于零的数字'))
      } else if (!Number.isInteger(numValue * 100)) {
        callback(new Error('价格最多保留两位小数'))
      } else {
        callback()
      }
    },
    enumFormat(val) {
      let itemTemp = {}
      this.$GlobalStatus.PRODUCT_STATUS.forEach(item => {
        if (item.type === val) {
          itemTemp = item
        }
      })
      return itemTemp
    }
  }
}
</script>

<style>
.el-tag + .el-tag {
  margin-left: 10px;
}

.button-new-tag {
  /*margin-left: 10px;*/
  /*height: 32px;*/
  /*line-height: 30px;*/
  /*padding-top: 0;*/
  /*padding-bottom: 0;*/
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}


/*sku图片*/
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 50px;
  height: 50px;
  line-height: 50px;
  text-align: center;
}

.avatar {
  width: 50px;
  height: 50px;
  display: block;
}
</style>
